<template>
  <div class="params-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon>
      </el-alert>

      <el-row class="select-cate">
        <el-col :span="24">
          <span>选择商品分类：</span>
          <el-cascader
            @change="changeCate"
            :props="cateProps"
            :options="cateList" 
            :show-all-levels="false"
            v-model="selectCate">
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="showAddDialog" type="primary" size="mini" :disabled="btnIsDisabled">添加参数</el-button>

          <el-table
            border
            :data="manyAttrList"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-tag
                  @close="delHandleClose(props.row, i)"
                  v-for="(tag, i) in props.row.attr_vals"
                  :key="tag"
                  closable>
                  {{tag}}
                </el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(props.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delAttr(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="showAddDialog" type="primary" size="mini" :disabled="btnIsDisabled">添加属性</el-button>
          
          <el-table
            border
            :data="onlyAttrList"
            style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-tag
                  @close="delHandleClose(props.row, i)"
                  v-for="(tag, i) in props.row.attr_vals"
                  :key="tag"
                  closable>
                  {{tag}}
                </el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(props.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delAttr(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        @close="addDialogColse"
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%">
        <el-form :model="addRuleForm" :rules="addRules" ref="AddruleFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addRuleForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        @close="editDialogColse"
        :title="'修改' + titleText"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editRuleForm" :rules="editRules" ref="editRuleFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editRuleForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectCate: [],
      activeName: 'many',
      onlyAttrList: [],
      manyAttrList: [],
      addDialogVisible: false,
      addRuleForm: {
        attr_name: ''
      },
      addRules: {
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editRuleForm: {},
      editRules:  {
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 3
        }
      })

      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.cateList = res.data
    },
    changeCate() {
      this.getAttrList()
    },
    tabHandleClick() {
      this.getAttrList()
      console.log(this.activeName)
    },
    async getAttrList() {
      if(this.selectCate.length < 3) {
        this.selectCate = []
        this.onlyAttrList = []
        this.manyAttrList = []
        return false
      }

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })

      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if(this.activeName === 'only') {
        this.onlyAttrList = res.data
      } else {
        this.manyAttrList = res.data
      }
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    addDialogColse() {
      this.$refs.AddruleFormRef.resetFields()
    },
    editDialogColse() {
      this.$refs.editRuleFormRef.resetFields()
    },
    addCate() {
      this.$refs.AddruleFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addRuleForm.attr_name,
            attr_sel: this.activeName
          })

          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)

          this.$message.success(res.meta.msg)
          this.getAttrList()
          this.addDialogVisible = false
        } else {  
          return this.$message.error('添加失败')
        }
      })
    },
    async showEditDialog(id) {
      this.editDialogVisible = true

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })

      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.editRuleForm = res.data
    },
    editCate() {
      this.$refs.editRuleFormRef.validate(async (valid) => {
          if (valid) {
            const { data: res } =  await this.$http.put(`categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`, {
              attr_name: this.editRuleForm.attr_name,
              attr_sel: this.activeName
            })

            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

            this.getAttrList()
            this.editDialogVisible = false
            this.$message.success(res.meta.msg)
          } else {
            return this.$message.error('请填写完整信息')
          }
        })
    },
    delAttr(id) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.$message.success(res.meta.msg)
        this.getAttrList()

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })       
      })
    },
    async handleInputConfirm(row) {
      if(row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''

        return false
      }

      row.attr_vals.push(row.inputValue)
      row.inputVisible = false
      row.inputValue = ''

      this.getAttrVals(row)
    },
    showInput(row) {
      row.inputVisible = true

      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    delHandleClose(row, i) {
      row.attr_vals.splice(i, 1)
      this.getAttrVals(row)
    },
    async getAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })

      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message.success(res.meta.msg)
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    btnIsDisabled: function() {
      if(this.selectCate.length === 3) {
        return false
      } else {
        return true
      }
    },
    cateId: function() {
      if(this.selectCate.length === 3) {
        return this.selectCate[2]
      }
      return null
    },
    titleText: function() {
      if(this.activeName === 'many') {
        return '动态参数'
      } else{
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scope>
  .params-container{
    .box-card{
      margin-top: 20px;
    }
    .select-cate{
      margin: 15px 0;
    }
    .el-table{
      margin-top: 20px;
    }
    .el-tag{
      margin: 7px;
    }
    .input-new-tag{
      width: 130px;
    }
  }
</style>